import {app, BrowserWindow, Menu} from 'electron'
import {join} from 'node:path'
import {fileURLToPath} from 'node:url'
import * as path from "node:path"
import {registerNodeService, cleanup} from './src/api/index.js'
import {initData} from './src/system/dataSystem.js'

// 获取当前文件路径
const __dirname = fileURLToPath(new URL('.', import.meta.url))

// 屏蔽安全警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

const createWindow = async () => {
    const win = new BrowserWindow({
        preload: path.join(__dirname, 'preload.js'),
        icon: join(__dirname, 'resource/shortcut.ico'),
        width: 1200,
        height: 800,
        minWidth: 800,
        minHeight: 600,
        webPreferences: {
            nodeIntegration: false, // 确保为 false，使用 contextBridge 替代
            contextIsolation: true, // 确保为 true，这是 contextBridge 工作的前提
            preload: path.join(__dirname, 'preload.js'),
            sandbox: false
        }
    })

    // 注册服务
    registerNodeService()

    const menuTemplate = [
        {
            label: '系统',
            submenu: [
                {
                    label: '重新加载软件',
                    click: async () => {
                        await win.loadURL('http://localhost:5173/')
                        // await win.loadFile(join(__dirname, 'index.html'))
                        app.relaunch()
                    }
                },
                {
                    label: '调试模式',
                    click: async () => {
                        await win.webContents.openDevTools()
                    }
                },
                {
                    label: '退出软件',
                    click: async () => {
                        await cleanup() // 清理资源
                        app.quit()
                    }
                }
            ]
        }
    ]

    Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate))

    if (process.env.VITE_DEV_SERVER_URL) {
        await win.loadURL(process.env.VITE_DEV_SERVER_URL)
        await win.webContents.openDevTools()
    } else {
        await win.loadURL('http://localhost:5173/')
        // await win.loadFile(join(__dirname, '../dist/index.html'))
    }

    return win
}

app.whenReady().then(async () => {
    await createWindow()
    initData()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', async () => {
    // 清理所有数据库连接
    await cleanup()
    if (process.platform !== 'darwin') app.quit()
})

// 处理应用退出
app.on('before-quit', async (event) => {
    event.preventDefault()
    await cleanup()
    app.exit(0)
})
